package com.ccit.goods.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccit.common.exception.GymException;
import com.ccit.common.exception.fileUpload.FileEmptyException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.PageUtil;
import com.ccit.common.utils.RedisUtils;
import com.ccit.common.utils.UploadUtil;
import com.ccit.goods.service.GoodsService;
import com.ccit.model.*;
import com.ccit.model.vo.goods.GoodsQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Api(tags = "商品管理")
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    GoodsService goodsService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UploadUtil uploadUtil;

    final String port = "8087";


    @ApiOperation("商品添加")
    @PostMapping("/saveGoods")
    public Result saveGoods(@RequestParam MultipartFile file,@RequestPart String  goodsStr) {
        if (file==null){
            throw new FileEmptyException();
        }
        String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
        Map<String, String> map = new HashMap<>();
        map.put("pathPrefix", pathPrefix);
        map.put("src", "goods");
        String fileName = uploadUtil.saveFile(file, map);
        JSONObject object = JSON.parseObject(goodsStr);

        Goods goods = new Goods();
        goods.setName(object.getString("name"));
        goods.setStock(object.getInteger("stock"));
        goods.setPrice(object.getDouble("price"));
        goods.setSupplier(object.getString("supplier"));
        goods.setImgUrl("http://localhost:" + port + "/goods/img/" + fileName);

        //商品查重s
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.eq("name", goods.getName());
        List<Goods> goodsList = goodsService.list(wrapper);
        if (goodsList.size() > 0) {
            //当已存在时
            throw new GymException(202, "用户名被占用!");
        } else {
            redisUtils.deleteRedisKeys("GoodsPage");
            redisUtils.deleteRedisKeys("goodsNames");
            redisUtils.deleteRedisKeys("GoodsPageName");
            boolean flag = goodsService.save(goods);
            if (flag == true) {
                return Result.ok();
            } else {
                return Result.fail().message("添加失败");
            }
        }
    }

    @ApiOperation("根据id删除商品")
    @DeleteMapping("/removeGoodsById/{id}")
    public Result removeGoodsById(@PathVariable("id") Integer id) {

        Goods goods = goodsService.getById(id);

        int lastIndexOf = goods.getImgUrl().lastIndexOf("/");
        String img_path = goods.getImgUrl().substring(lastIndexOf + 1, goods.getImgUrl().length());
        System.out.println(img_path);

        String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
        Map<String, String> map = new HashMap<>();
        map.put("pathPrefix", pathPrefix);
        map.put("src", "goods");
        img_path = pathPrefix + "\\src\\main\\resources\\static\\" + map.get("src") + "\\img\\" + img_path;

        File file = new File(img_path);

        boolean byId = goodsService.removeById(id);
        if (byId) {
            redisUtils.deleteRedisKeys("GoodsPage");
            if (file.exists()) {
                if (file.delete()) {
                    redisUtils.deleteRedisKeys("GoodsPage");
                    redisUtils.deleteRedisKeys("goodsNames");
                    redisUtils.deleteRedisKeys("GoodsPageName");
                    return Result.ok("删除成功");
                } else {
                    return Result.fail().message("删除失败");
                }
            } else {
                return Result.fail().message("文件不存在");
            }
        } else throw new GymException(202, "无此器材");
    }

    @ApiOperation("根据id批量删除商品")
    @DeleteMapping("/batchRemove")
    public Result removeGoodsByIds(@RequestParam(required = false) List<Integer> idList) {
        //批量模糊删除所有包含keys的数据
        idList.forEach(id -> {
            Goods goods = goodsService.getById(id);
            if (goods == null) {
                throw new GymException(202, "无此商品");
            }
        });
        boolean b = goodsService.removeByIds(idList);
        if (b) {
            redisUtils.deleteRedisKeys("GoodsPage");
            redisUtils.deleteRedisKeys("goodsNames");
            redisUtils.deleteRedisKeys("GoodsPageName");
            return Result.ok();
        } else {
            return Result.fail().message("删除失败");
        }
    }

    @ApiOperation(value = "分页条件查询商品")
    @PostMapping("/findPageGoods/{current}/{size}")
    public Result selectGoods(@RequestBody Goods goods,
                              @PathVariable long current,
                              @PathVariable long size
                              ) {
        Page<Goods> page;
        String key = "GoodsPage:" + current + ":" + size;
        if (goods.getName()!=null){
            key = "GoodsPageName:"+current + ":" + size;
        }
        boolean hasKey = redisUtils.hasKey(key);
        if (hasKey){
            System.out.println("==============redis=====================");
            page = (Page<Goods>)redisUtils.get(key);
        }else {
            QueryWrapper<Goods> wrapper = new QueryWrapper<Goods>();
            if (goods.getName()!=null){
                wrapper.lambda()
                        .like(Goods::getName, goods.getName());
            }
            Page<Goods> goodsPage = new Page<>(current, size);
            page = goodsService.page(goodsPage, wrapper);
            redisUtils.set(key,page);
        }
        return Result.ok(page);
    }

    @ApiOperation(value = "修改商品")
    @PostMapping("/updateGoods")
    public Result updateGoods(@RequestParam(required = false) MultipartFile file, @RequestPart String goodsStr) {
        JSONObject object = JSON.parseObject(goodsStr);
        Goods goods = goodsService.getById(object.getLong("id"));
        goods.setSupplier(object.getString("supplier"));
        goods.setPrice(object.getDouble("price"));
        goods.setStock(object.getInteger("stock"));
        goods.setName(object.getString("name"));

        if (file != null) {
            String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
            Map<String, String> map = new HashMap<>();
            map.put("pathPrefix", pathPrefix);
            map.put("src", "goods");
            String fileName = uploadUtil.saveFile(file, map);
            goods.setImgUrl("http://localhost:" + port + "/goods/img/" + fileName);
           /* int lastIndexOf = goods.getImgUrl().lastIndexOf("/");
            String img_path = goods.getImgUrl().substring(lastIndexOf + 1, goods.getImgUrl().length());
            //旧文件路径
            img_path = pathPrefix + "\\src\\main\\resources\\static\\" + map.get("src") + "\\img\\" + img_path;



            //删除旧文件
            File OldFile = new File(img_path);
            if (OldFile.exists()) {
                if (OldFile.delete()) {
                    String fileName = uploadUtil.saveFile(file, map);
                    goods.setImgUrl("http://localhost:" + port + "/goods/img/" + fileName);
                } else {
                    return Result.fail().message("删除失败");
                }
            } else {
                String fileName = uploadUtil.saveFile(file, map);
                goods.setImgUrl("http://localhost:" + port + "/goods/img/" + fileName);
            }*/
        }

        boolean flag = goodsService.updateById(goods);
        if (flag) {
            redisUtils.deleteRedisKeys("GoodsPage");
            redisUtils.deleteRedisKeys("goodsNames");
            redisUtils.deleteRedisKeys("GoodsPageName");
            return Result.ok();
        } else {
            return Result.fail().message("修改失败");
        }

    }

    @ApiOperation(value = "获取所有商品名称")
    @GetMapping("/getAllGoodsNames")
    public Result getAllGoodsNames() {
        String key = "goodsNames";
        boolean hasKey = redisUtils.hasKey(key);
        List<Map> nameList;
        if (hasKey) {
            System.out.println("===============redis================");
            nameList =(List<Map>)redisUtils.get(key);
        } else {
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("name");
            List<Goods> list = goodsService.list(queryWrapper);

            Map<String, List<Goods>> collect = list.stream().collect(Collectors.groupingBy(goods -> goods.getName()));
            nameList = new ArrayList<>();
            collect.forEach((s,value)->{
                Map<String , String> goodsName = new HashMap<>();
                goodsName.put("value",s);
                nameList.add(goodsName);
            });
            if (nameList.size() == 0)
                throw new GymException(202, "数据请求失败");
        }
        redisUtils.set(key,nameList);
        return Result.ok(nameList);


    }
    @ApiOperation("根据id获取员工信息")
    @GetMapping("/getById/{id}")
    public Goods getGoodsById(@PathVariable Long  id) {
        Goods goods = goodsService.getById(id);
        if (goods==null){
            throw new GymException(202,"没有此员工");
        }
        return goods;
    }



}
